package com.syh.app.basic.views;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.syh.app.basic.R;
import com.syh.app.basic.utils.AppUtil;
import com.syh.app.basic.utils.Tooast;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 创建者：SYH
 * 时间：2020/6/2 20:02
 * 编辑者：SYH、
 * 标签：
 * 补充说明：
 */
public class ImageWatcher extends Dialog {

    private WindowManager.LayoutParams mLayoutParams;
    private Context mContext;
    private ImageView ivWatcher;
    private ImageView ivClose;
    private Button btnSave;

    public ImageWatcher(Context context) {
        super(context, R.style.FullDialog);
        init(context);
        initContentView();
    }


    private void init(Context context) {
        this.mContext = context;
        Window dialogWindow = this.getWindow();
        mLayoutParams = dialogWindow.getAttributes();
        mLayoutParams.width = AppUtil.getScreenWidths(context);
        dialogWindow.setAttributes(mLayoutParams);
        dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
        dialogWindow.getDecorView().setBackgroundResource(android.R.color.transparent);
        dialogWindow.setGravity(Gravity.CENTER);
    }

    private void initContentView() {
        View dialogView = LayoutInflater.from(this.getContext()).inflate(R.layout.dialog_image_watcher, (ViewGroup) null);

        ivWatcher = dialogView.findViewById(R.id.ivWatcher);
        ivClose = dialogView.findViewById(R.id.ivClose);
        btnSave = dialogView.findViewById(R.id.btnSave);
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancel();
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (resource != null) {
                    Observable.create(new ObservableOnSubscribe<Boolean>() {
                        @Override
                        public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                            Bitmap bitmap = ((BitmapDrawable) resource).getBitmap();
                            if (AppUtil.saveImageToGallery(mContext, bitmap)) {
                                emitter.onNext(true);
                            } else {
                                emitter.onNext(false);
                            }
                            emitter.onComplete();
                        }
                    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<Boolean>() {

                                Disposable disposable;
                                @Override
                                public void onSubscribe(Disposable d) {
                                    disposable = d;
                                    btnSave.setEnabled(false);
                                    Tooast.normalInfo("正在保存图片");
                                }

                                @Override
                                public void onNext(Boolean aBoolean) {
                                    if (aBoolean) {
                                        Tooast.success("图片已保存");
                                    } else {
                                        Tooast.warning("保存失败");
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    btnSave.setEnabled(true);
                                    Tooast.warning("保存失败");
                                    if (disposable != null && !disposable.isDisposed())
                                        disposable.dispose();
                                }

                                @Override
                                public void onComplete() {
                                    btnSave.setEnabled(true);
                                    if (disposable != null && !disposable.isDisposed())
                                        disposable.dispose();
                                }
                            });
                }
            }
        });

        setContentView(dialogView);
    }

    public void show(String url) {
        Glide.with(mContext).load(url).apply(RequestOptions.errorOf(R.mipmap.basic_ic_no_data)
                .diskCacheStrategy(DiskCacheStrategy.NONE)).addListener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                ivClose.setVisibility(View.VISIBLE);
                btnSave.setVisibility(View.VISIBLE);
                ImageWatcher.this.resource = resource;
                return false;
            }
        })
                .into(ivWatcher);
        show();
    }

    Drawable resource;

    public void show(Bitmap bitmap) {
        Glide.with(mContext).load(bitmap).apply(RequestOptions.errorOf(R.mipmap.basic_ic_no_data)
                .diskCacheStrategy(DiskCacheStrategy.NONE)).addListener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                ivClose.setVisibility(View.VISIBLE);
                btnSave.setVisibility(View.VISIBLE);
                ImageWatcher.this.resource = resource;
                return false;
            }
        })
                .into(ivWatcher);
        show();
    }
}
